package servlets;

import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import logica.datatypes.Partida.DataPartida_R16;
import logica.fachadas.IFabrica;
import logica.fachadas.IFachadaPublico;
import persistencia.Config;
import persistencia.PersistenciaException;


public class Partidas extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		doPost(req, resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		ServletContext context = super.getServletContext();
		HttpSession session = req.getSession();
	    boolean error = false;
	    String msgError = new String();
		RequestDispatcher rd;
		try{	
			Config conf = Config.getInstancia();
			String servidor = conf.getArchivoConf("Servidor"); 
	        int puerto =  Integer.parseInt(conf.getArchivoConf("Puerto"));      
	        IFabrica modelo = (IFabrica)Naming.lookup("//" + servidor +":" + puerto + "/fabrica"); 
	        IFachadaPublico fachadaPublico= modelo.getFachadaPublico();
	       
	        DataPartida_R16[] dataPartida_R16 = fachadaPublico.listarPartidasRegistradas();
			 	
		 	ArrayList arr=new ArrayList<DataPartida_R16>();
		 	for(int i=0; i<dataPartida_R16.length; i++)
		 		arr.add(dataPartida_R16[i]);
		 	
		    synchronized (context){
		    	context.setAttribute("DataPartidas", arr);
		    }    

			rd = req.getRequestDispatcher("Partidas.jsp");
			rd.forward(req, resp);
		
		} catch (MalformedURLException e) {
		    msgError = "Error: MalformedURLException";
		    req.setAttribute("msgError", msgError);
		    rd = req.getRequestDispatcher("Error.jsp");
		    rd.forward(req, resp);
		} catch (RemoteException e) {
		    msgError = "Error: No se ha podido establecer conexion con el Servidor";
		    req.setAttribute("msgError", msgError);
		    rd = req.getRequestDispatcher("Error.jsp");
		    rd.forward(req, resp);
		} catch (NotBoundException e) {
		    msgError = "Error: No se ha podido recuperar la informacion del sistema del servidor";
		    req.setAttribute("msgError", msgError);
		    rd = req.getRequestDispatcher("Error.jsp");
		    rd.forward(req, resp);
		} catch (PersistenciaException e) {
		    msgError = e.getMessage();
		    req.setAttribute("msgError", msgError);
		    rd = req.getRequestDispatcher("Error.jsp");
		    rd.forward(req, resp);
		}
		
	}
}
